package dataStructure.sort.quickSort;

import java.util.Arrays;

/**
 * @author lhn
 * @date 2024-08-31 14:57
 */

public class QuickSort {
    public static void main(String[] args) {
//        int[] arr = {-9, 78, 0, 23, -567, 70};
        int[] arr = {23, 78, 0, 23, -567, 23};
        System.out.println("排序前：");
        System.out.println(Arrays.toString(arr));

        QuickSort.sort(arr, 0 , arr.length - 1);

        System.out.println("排序后：");
        System.out.println(Arrays.toString(arr));
    }

    public static void sort(int[] arr, int left, int right) {

        int l = left;
        int r = right;
        int pivot = arr[(left + right) / 2];

        while (l < r) {
            //在左边找到一个小于pivot的数
            while (arr[l] < pivot) {
                l++;
            }
            //在右边找到一个大于pivot的数
            while (arr[r] > pivot) {
                r--;
            }
            if (l >= r) {
                break;
            }
            //交换
            int temp = arr[l];
            arr[l] = arr[r];
            arr[r] = temp;

            //手动优化，防止死循环
            if (arr[l] == pivot) {
                r--;
            }
            if (arr[r] == pivot) {
                l++;
            }

        }

        //跳出while时，l == r
        System.out.println("l is " + l + "r is " + r);
        if (l == r) {
            l++;
            r--;
        }
//        System.out.println("left is " + left + "  right is " + right);
//        System.out.println("l is " + l + "  r is " + r);
        //左边
        if (left < r) {
            sort(arr, left, r);
        }

        if (right > l) {
            sort(arr, l, right);
        }
    }
}
